package com.coinland.study.view;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coinland.study.R;
import com.coinland.study.base.BaseActivity;
import com.coinland.study.bean.DocumentBean;
import com.coinland.study.util.Contant;
import com.coinland.study.util.DisplayUtils;
import com.coinland.study.util.ScreenUtils;
import com.coinland.study.util.SharedPreUtils;
import com.coinland.study.util.ToastUtil;
import com.coinland.study.window.BitmapUtils;
import com.coinland.study.window.DialogPermission;
import com.coinland.study.window.IShowSuccess;
import com.coinland.study.window.WindowUtil;
import com.coinland.study.window.rom.RomUtils;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.coinland.study.util.Contant.BROAD_CAST_NAME;
import static com.coinland.study.window.rom.RomUtils.REQUEST_PERMISSION_CODE;

/**
 * 类描述:  腾讯TBS  doc ppt excel文件
 * 创建人:  shenZ
 * 创建时间: 2020/4/13
 * 联系方式: 252079249@qq.com
 * 修改时间: 2020/4/13
 */
public class TabsReaderViewActivity extends BaseActivity implements View.OnClickListener,
        IShowSuccess {

    public final String TAG = TabsReaderViewActivity.this.getClass().getSimpleName();
    public static final String DOCUMENT_BEAN = "DOCUMENT_BEAN";

    private Context mContext;

    @BindView(R.id.iv_search)
    public ImageView ivSearch;

    @BindView(R.id.tbsView)
    public RelativeLayout tbsView;

    // 文档路径
    private String docUrl;
    // 文件名字(不包括后缀名)
    private String docName;
    // tbs阅读器
    private TbsReaderView mTbsReaderView;
    // 广播接收
    private BroadcastReceiver receiver;

    //搜索按钮
    @OnClick({R.id.iv_back, R.id.iv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_search:
                showMorePop();
                break;
        }
    }

    public static void start(Context context, DocumentBean documentBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(DOCUMENT_BEAN, documentBean);
        Intent intent = new Intent(context, TabsReaderViewActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_tabs_reader;
    }

    @Override
    public void initView() {
        mContext = TabsReaderViewActivity.this;
        docUrl = getIntent().getStringExtra(Contant.DOC_PATH);
        docName = getIntent().getStringExtra(Contant.DOC_NAME);
        ivSearch.setVisibility(View.VISIBLE);
        ivSearch.setImageResource(R.mipmap.more);

        DocumentBean docBean = (DocumentBean) getIntent().getSerializableExtra(DOCUMENT_BEAN);
        if (null != docBean) {
            docUrl = docBean.getLocalPath();
            docName = docBean.getTitle();
        }
        // 接收广播
        initReceiver();

        addTbsReaderView();
        initDoc();
        setCustomTheme();
    }

    private void initReceiver() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();//得到Service发送的广播
                if (Contant.BROAD_CAST_NAME.equals(action)) {
                    Log.e("BaseActivity", "开启悬浮广播-------------------->");
                    DialogPermission.showDialog(context);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROAD_CAST_NAME);//从系统底层获得这条广播
        registerReceiver(receiver, filter);//注册广播接收器
    }


    private void addTbsReaderView() {
        mTbsReaderView = new TbsReaderView(mContext, null);
        tbsView.addView(mTbsReaderView, new RelativeLayout.LayoutParams(-1, -1));
    }


    private void initDoc() {
        int index = docUrl.lastIndexOf("/");
        String docName = docUrl.substring(index + 1, docUrl.length());
        String docPath = docUrl.substring(0, index);

        //判断是否在本地/[下载/直接打开]
        File docFile = new File(docPath, docName);
        if (docFile.exists()) {
            //存在本地;
            Log.d(TAG, "本地存在");
            displayFile(docFile.toString(), docName);
        } else {
            ToastUtil.showShort("本地不存在", TabsReaderViewActivity.this);
        }
    }


    private void displayFile(String filePath, String fileName) {
        //增加下面一句解决没有TbsReaderTemp文件夹存在导致加载文件失败
        String bsReaderTemp = getExternalCacheDir() + "/TbsReaderTemp";
        File bsReaderTempFile = new File(bsReaderTemp);
        if (!bsReaderTempFile.exists()) {
            Log.d(TAG, "准备创建/TbsReaderTemp！！");
            boolean mkdir = bsReaderTempFile.mkdir();
            if (!mkdir) {
                Log.d(TAG, "创建/TbsReaderTemp失败！！！！！");
            }
        }
        Bundle bundle = new Bundle();
        bundle.putString("filePath", filePath);
        bundle.putString("tempPath", bsReaderTemp);
        boolean result = mTbsReaderView.preOpen(getFileType(fileName), false);
        Log.d("print", "查看文档---" + result);
        if (result) {
            mTbsReaderView.openFile(bundle);
        } else {

        }
    }

    private String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            Log.d(TAG, "paramString---->null");
            return str;
        }
        Log.d(TAG, "paramString:" + paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            Log.d(TAG, "i <= -1");
            return str;
        }

        str = paramString.substring(i + 1);
        Log.d(TAG, "paramString.substring(i + 1)------>" + str);
        return str;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 权限回调
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (RomUtils.checkFloatWindowPermission(mContext)) {
                List<DocumentBean> paths = spUtils.getList(mContext, Contant.DOC_PATH, DocumentBean.class);
                DocumentBean documentBean = new DocumentBean();
                documentBean.setLocalPath(docUrl);
                documentBean.setTitle(docName);
                paths.add(documentBean);
                spUtils.saveList(mContext, Contant.DOC_PATH, paths);

                // 开启悬浮框
                WindowUtil.getInstance().showSuccessWindow(mContext, this);
            }
        }
    }


    private PopupWindow morePop;
    private View rootView;

    /**
     * 更多弹出框
     */
    private void showMorePop() {
        if (morePop == null) {
            rootView = getLayoutInflater().inflate(R.layout.layout_more_popwindow, null);
            RelativeLayout rlFk = (RelativeLayout) rootView.findViewById(R.id.rl_fk);
            ImageView ivFk = (ImageView) rootView.findViewById(R.id.iv_fk);
            TextView tvFk = (TextView) rootView.findViewById(R.id.tv_fk);
            rlFk.setOnClickListener(this);

            morePop = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
            morePop.setOutsideTouchable(true);
            morePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    removeMaskView();
                }
            });

            morePop.setBackgroundDrawable(new BitmapDrawable());
            morePop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        morePop.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            addMaskView();
            morePop.showAtLocation(findViewById(R.id.iv_back), Gravity.BOTTOM, 0, 0);
        } else {
            if (morePop.isShowing()) {
                morePop.dismiss();
            } else {
                addMaskView();
                morePop.showAtLocation(findViewById(R.id.iv_back), Gravity.BOTTOM, 0, 0);
            }
        }
        setCustomTheme();
    }


    /**
     * 设置浮框按钮的样式
     * 根据SharedPre中是否有保存值，判断按钮显示
     */
    public void setCustomTheme() {
        List<DocumentBean> paths = spUtils.getList(mContext, Contant.DOC_PATH, DocumentBean.class);
        boolean isExsit = false;
        int index = -1;
        for (DocumentBean path : paths) {
            if (docUrl.equals(path.getLocalPath())) {
                isExsit = true;
                index = paths.indexOf(path);
                break;
            }
        }

        if (rootView != null) {
            if (isExsit) {
                ((ImageView) rootView.findViewById(R.id.iv_fk)).setImageResource(R.mipmap.point_red);
                ((TextView) rootView.findViewById(R.id.tv_fk)).setText("取消浮框");
            } else {
                ((ImageView) rootView.findViewById(R.id.iv_fk)).setImageResource(R.mipmap.point_green);
                ((TextView) rootView.findViewById(R.id.tv_fk)).setText("浮框");
            }
        }

        List<DocumentBean> temps = new ArrayList<>();
        temps.addAll(paths);
        if (index != -1) {
            temps.remove(index);
        }
        WindowUtil.getInstance().setDataOut(temps);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_fk:
                List<DocumentBean> paths = spUtils.getList(mContext, Contant.DOC_PATH, DocumentBean.class);
                int index = -1;
                for (int i = 0; i < paths.size(); i++) {
                    if (docUrl.equals(paths.get(i).getLocalPath())) {
                        index = i;
                        break;
                    }
                }
                if (index != -1) {
                    paths.remove(index);
                    ToastUtil.showShort("取消浮框成功", mContext);
                    spUtils.saveList(mContext, Contant.DOC_PATH, paths);
                    setCustomTheme();
                } else {
                    morePop.dismiss(); //  关闭popwindow
                    // 开启悬浮框权限
                    if (RomUtils.checkFloatWindowPermission(mContext)) {
                        DocumentBean documentBean = new DocumentBean();
                        documentBean.setLocalPath(docUrl);
                        documentBean.setTitle(docName);
                        paths.add(documentBean);
                        spUtils.saveList(mContext, Contant.DOC_PATH, paths);

                        // 开启悬浮框
                        WindowUtil.getInstance().showSuccessWindow(mContext, this);
                    } else {
                        //开启悬浮框权限
                        DialogPermission.showDialog(mContext);
                    }
                }
                break;
        }
    }

    @Override
    public void showSuccess() {
        SharedPreUtils.saveBoolean(mContext,Contant.IS_EXECUTE_ANIM,true);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTbsReaderView.onStop();
        // 注销广播
        unregisterReceiver(receiver);
    }


}



